package com.yousu.dashijixm.interceptors;

import com.yousu.dashijixm.utils.JwtUtil;
import com.yousu.dashijixm.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * @Author: YouSu
 * @Version: 1.0
 * @CreateTime: 2023-11-19  10:39
 */
//设置登录拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的令牌
        String token = request.getHeader("Authorization");
        try {
            //从redis中获取token，判断是否是最新的令牌
            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            String lastToken = ops.get(token);
            if (lastToken == null){ //获取不到说明redis中的令牌不是最新的了
                throw new RuntimeException();
            }
            //判断令牌是否被修改或为假
            Map<String, Object> claims = JwtUtil.parseToken(token);
            //使用ThreadLocal保存获取到的令牌,就可以不用每次都要去获取令牌拿用户信息
            ThreadLocalUtil.set(claims);
            return true; //放行
        } catch (Exception e) {
            response.setStatus(401); // 设置状态码为401
            return false; //拦截
        }
    }

    @Override//所有请求完成后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //释放ThreadLocal内存,防止内存泄漏
        //因为ThreadLocal都是线程独立的
        ThreadLocalUtil.remove();
    }
}

